package com.ruoyi.biz.export.executor;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.ruoyi.biz.export.enums.ExportTemplateEnum;
import com.ruoyi.biz.export.vo.ReqVO;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.Map;

/**
 * @author Fei.Cong
 * @date 2024-07-16 20:05
 */
@Slf4j
public abstract class AbstractExecutor {

    public void execute(ReqVO reqVo) {

        // build params
        Map<String, Object> paramMap = beforeExecute(reqVo);

        //fill excel
        ExcelWriter excelWriter = coreExecute(reqVo);

        // handle result
        afterExecute(excelWriter, paramMap);

    }

    /**
     * @param reqVo
     * @return
     */
    public abstract Map<String, Object> beforeExecute(ReqVO reqVo);

    protected ExcelWriter coreExecute(ReqVO reqVo) {
        ExportTemplateEnum templateEnum = reqVo.getTemplateEnum();
        InputStream inputStream = this.getClass().getResourceAsStream(templateEnum.getTemplate());
        return EasyExcel.write(reqVo.getOs(), reqVo.getClazz()).withTemplate(inputStream)
                .registerConverter(new LongStringConverter())
                .build();
    }

    /**
     * @param excelWriter
     * @param paramMap
     */
    protected abstract void afterExecute(ExcelWriter excelWriter, Map<String, Object> paramMap);

}
